import { constantRoutes } from '@/router'
import { buildMenus } from '@/api/auth/menu'
import Layout from '@/layout'
import { Message } from 'element-ui'

function filterAsyncRouter(asyncRouterMap) { // 遍历后台传来的路由字符串，转换为组件对象
  try {
    const accessedRouters = asyncRouterMap.filter(route => {
      if (route.component) {
        if (route.component === 'Layout') { // Layout组件特殊处理
          route.component = Layout
        } else {
          const component = route.component
          route.component = loadView(component)
        }
      }
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children)
      }

      return true
    })
    return accessedRouters
  } catch (e) {
    console.log(e)
  }
}

export const loadView = (view) => {
  return (resolve) => require([`@/views${view}`], resolve)
}
const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  async generateRoutes({ commit }) {
    // 取后台路由
    const asyncRouter = await buildMenus()
    // commit('SET_ROUTES', asyncRouter)
    return new Promise(resolve => {
      const tmp = asyncRouter.data.permissionList
      if (tmp && tmp.length > 0) {
        const accessedRoutes = filterAsyncRouter(tmp)
        // accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      } else {
        Message.error('当前用户没有菜单权限请分配')
        resolve()
      }
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
